package com.sophie.controller;

import com.sophie.entity.User;
import com.sophie.entity.Zone;
import com.sophie.service.IUserService;
import com.sophie.service.IZoneService;
import com.sophie.service.impl.UserServiceImpl;
import com.sophie.service.impl.ZoneServiceImpl;
import com.sophie.util.FileUploadUtil;
import com.sophie.util.ResultVO;
import com.sophie.util.SendJSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;

@WebServlet(name = "ZoneServlet", value = "/ZoneServlet")
@MultipartConfig
public class ZoneServlet extends BaseServlet {
    IZoneService zoneService= new ZoneServiceImpl();
    IUserService userService = new UserServiceImpl();
    //ZoneServlet?method=publish
    protected void publish(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->发布动态");
        request.setCharacterEncoding("utf-8");
        final long MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
        String contenttext = request.getParameter("contenttext");
//        System.out.println(contenttext);
        //String imgsPath = null;
        Collection<Part> parts = request.getParts();

        StringBuilder imgsPathBuilder = new StringBuilder();
        if (parts != null) {
            for (Part part : parts) {
                String fileName = part.getSubmittedFileName();
                if (fileName == null || fileName.isEmpty()) {
                    // 可能是非文件字段，跳过或进行其他处理
//                    System.out.println("Skipping non-file part: " + part.getName());
                    continue;
                }
                // 检查文件大小（可选，但有助于防止上传空文件）
                long fileSize = part.getSize();
                if (fileSize <= 0) {
//                    System.out.println("Skipping empty file part: " + fileName);
                    continue;
                }
                if (fileSize > MAX_FILE_SIZE) {
                    throw new ServletException("File is too large: " + fileName + " (" + fileSize + " bytes). Maximum allowed size is " + MAX_FILE_SIZE + " bytes.");
                }
                // 处理文件上传
                String imgPath = FileUploadUtil.uploadImage(part, request);
//                System.out.println("imgPath=" + imgPath);
                // 添加到路径构建器中，注意不要在第一个元素前添加_
                if (imgsPathBuilder.length() > 0) {
                    imgsPathBuilder.append("+");
                }
                imgsPathBuilder.append(imgPath);
            }
        }
        String imgsPath = imgsPathBuilder.toString();
        System.out.println("imgsPath=" + imgsPath);
        User user = (User) request.getSession().getAttribute("user");
        Zone zone = new Zone(null, contenttext, 0, 0, 0, new Date(), 1, user.getId(), imgsPath);

        ResultVO resultVO = zoneService.addZone(zone);
        SendJSONUtil.send(resultVO,response);
    }

    //ZoneServlet?method=objectZone
    protected void objectZone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->跳转到别人空间");
        String oid = request.getParameter("oid");
        System.out.println("oid = " + oid);
        int id = Integer.parseInt(oid);
        //
        ResultVO object = userService.getUserById(id);
        ResultVO zones = zoneService.getZonesByUserId(id);
        request.setAttribute("object", object.getData());
        request.setAttribute("objectZone", zones.getData());
        request.getRequestDispatcher("object.jsp").forward(request, response);
    }

    //ZoneServlet?method=countZone
    protected void countZone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->统计发布过的动态数量");
        String id = request.getParameter("id");
        //
        ResultVO resultVO = zoneService.countZone(Integer.parseInt(id));
//        System.out.println("resultVO.getData() = " + resultVO.getData());
        SendJSONUtil.send(resultVO.getData(),response);
    }

    //ZoneServlet?method=zone
    protected void zone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->跳转广场");
        //调用
        ResultVO allZones = zoneService.getAllZones();
//        System.out.println("allZones.getData() = " + allZones.getData());
        request.setAttribute("zones", allZones.getData());
        request.getRequestDispatcher("square.jsp").forward(request, response);
    }

    //ZoneServlet?method=countTransmit
    protected void countTransmit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->计算转发次数");
        String zoneid = request.getParameter("zoneid");
        ResultVO resultVO = zoneService.countTransmit(Integer.parseInt(zoneid));
        SendJSONUtil.send(resultVO.getData(),response);
    }

    //ZoneServlet?method=checkCollected
    protected void checkCollected(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->检查是否被收藏");
        String zoneid = request.getParameter("zoneid");
        User user = (User) request.getSession().getAttribute("user");
        ResultVO resultVO = zoneService.checkCollected(Integer.parseInt(zoneid),user.getId());
        SendJSONUtil.send(resultVO.getData(),response);
    }

    //ZoneServlet?method=cancelZone
    protected void cancelZone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->取消收藏动态");
        String zoneid = request.getParameter("zoneid");
        User user = (User) request.getSession().getAttribute("user");
        ResultVO resultVO = zoneService.cancelZone(Integer.parseInt(zoneid), user.getId());
        SendJSONUtil.send(resultVO.getData(),response);
    }

    //ZoneServlet?method=collectZone
    protected void collectZone(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->收藏动态");
        User user = (User) request.getSession().getAttribute("user");
        String zoneid = request.getParameter("zoneid");
        ResultVO resultVO = zoneService.collectZone(Integer.parseInt(zoneid), user.getId());
        SendJSONUtil.send(resultVO.getData(),response);
    }


    //ZoneServlet?method=none
    protected void none(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->");
    }
}